package com.lele.config.security;

import com.lele.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class JwtAuthenticationFilter extends OncePerRequestFilter {
/*    @Value("${jwt.data.tokenHeader}")
    private String authorization;
    @Value("${jwt.data.tokenHead}")
    private String bearer;*/
    @Resource
    private JWTUtil jwtUtil;
    //TODO 构造方法注入和bean注入的区别
    private MyUserDetailsService userDetailsService;

    @Autowired
    public void setUserDetailsService(MyUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("Authorization");
        if(header!=null&&header.startsWith("Bearer")){
            //获取到用户名了
            String loginToken = header.substring("Bearer".length()+1);
            String username = jwtUtil.getUsernameFromToken(loginToken);
            //如果还没有登录，并且用户名不为空
            if(username!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //token是有效的
                if(jwtUtil.validateToken(loginToken,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }

            }
        }
        filterChain.doFilter(request,response);
    }
}
